package com.ruoyi.kenuo.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.beust.jcommander.internal.Maps;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.kenuo.domain.EmailLog;
import com.ruoyi.kenuo.domain.PoloSmsLog;
import com.ruoyi.kenuo.enums.SmsMy;
import com.ruoyi.kenuo.mapper.PoloSmsLogMapper;
import com.ruoyi.kenuo.service.IPoloSmsLogService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author polo
 * @date 2022-10-19
 */
@Service
public class PoloSmsLogServiceImpl implements IPoloSmsLogService
{
    @Resource
    private PoloSmsLogMapper poloSmsLogMapper;
    @Autowired
    private JavaMailSender sender;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public PoloSmsLog selectPoloSmsLogById(String id)
    {
        return poloSmsLogMapper.selectPoloSmsLogById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param poloSmsLog 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<PoloSmsLog> selectPoloSmsLogList(PoloSmsLog poloSmsLog)
    {
        return poloSmsLogMapper.selectPoloSmsLogList(poloSmsLog);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param poloSmsLog 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertPoloSmsLog(PoloSmsLog poloSmsLog)
    {
        String id = poloSmsLog.getId();
        if(StringUtils.isEmpty(id)){
            poloSmsLog.setId(IdUtils.fas32tUUID());
        }
        return poloSmsLogMapper.insertPoloSmsLog(poloSmsLog);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param poloSmsLog 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updatePoloSmsLog(PoloSmsLog poloSmsLog)
    {
        return poloSmsLogMapper.updatePoloSmsLog(poloSmsLog);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deletePoloSmsLogByIds(String[] ids)
    {
        return poloSmsLogMapper.deletePoloSmsLogByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deletePoloSmsLogById(String id)
    {
        return poloSmsLogMapper.deletePoloSmsLogById(id);
    }

    @Override
    public AjaxResult sendSms(SmsMy valid, Long valueOf, String mobile, Map<String,String> hashMap) {

        PoloSmsLog smsLog = new PoloSmsLog();
        String code = RandomUtil.randomNumbers(6);
        hashMap.put("code",code);
        if(valid.equals(SmsMy.VALID)){
            //将上一条验证码失效
            poloSmsLogMapper.invalidSmsByMobile(mobile,valid.value());
        }
        smsLog.setId(IdUtils.fas32tUUID());
        smsLog.setType(0);
        smsLog.setMobileCode(code);
        smsLog.setRecDate(DateUtils.getNowDate());
        smsLog.setStatus(1);
        smsLog.setUserId(valueOf.toString());
        smsLog.setUserPhone(mobile);
        smsLog.setContent(formatContent(valid,hashMap));
        //新增新的验证码
        poloSmsLogMapper.insertPoloSmsLog(smsLog);
        try {
            this.sendCurSms(mobile,valid.getTemplateCode(),hashMap);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("发送短信失败，请稍后再试！");
        }

        return AjaxResult.success("发送成功！");
    }

    @Override
    public AjaxResult checkMyCode(PoloSmsLog poloSmsLog) {
        String mobile = poloSmsLog.getUserPhone();
        String code = poloSmsLog.getMobileCode();

        PoloSmsLog sg = new PoloSmsLog();
        sg.setStatus(1);
        sg.setUserPhone(mobile);
        List<PoloSmsLog> lg = poloSmsLogMapper.selectPoloSmsLogList(sg);
        PoloSmsLog log = lg.get(0);
        //删除无效的验证码
        PoloSmsLog sgw = new PoloSmsLog();
        sgw.setStatus(0);
        sgw.setUserPhone(mobile);
        List<PoloSmsLog> lgw = poloSmsLogMapper.selectPoloSmsLogList(sgw);
        lgw.forEach(x->{
            poloSmsLogMapper.deletePoloSmsLogById(x.getId());
        });
        if(code.equals(log.getMobileCode())){
            return AjaxResult.success("效验验证码正确");
        }else {
            return AjaxResult.error("验证码不正确");
        }
    }

    @Override
    public Boolean checkCurCode(PoloSmsLog poloSmsLog) {
        String mobile = poloSmsLog.getUserPhone();
        String code = poloSmsLog.getMobileCode();

        PoloSmsLog sg = new PoloSmsLog();
        sg.setStatus(1);
        sg.setUserPhone(mobile);
        List<PoloSmsLog> lg = poloSmsLogMapper.selectPoloSmsLogList(sg);
        PoloSmsLog log = lg.get(0);
        //删除无效的验证码
        PoloSmsLog sgw = new PoloSmsLog();
        sgw.setStatus(0);
        sgw.setUserPhone(mobile);
        List<PoloSmsLog> lgw = poloSmsLogMapper.selectPoloSmsLogList(sgw);
        lgw.forEach(x->{
            poloSmsLogMapper.deletePoloSmsLogById(x.getId());
        });
        if(code.equals(log.getMobileCode())){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public AjaxResult sendHUYiSms(SmsMy valid, Long valueOf, String mobile, HashMap hashMap) {
        String code = RandomUtil.randomNumbers(6);
        String content = new String("您的验证码是：" + code + "。请不要把验证码泄露给其他人。");
        System.out.println(content);
        try {
            this.sendHuYISms(mobile,content);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        PoloSmsLog smsLog = new PoloSmsLog();

        if(valid.equals(SmsMy.VALID)){
            //将上一条验证码失效
            poloSmsLogMapper.invalidSmsByMobile(mobile,valid.value());
        }
        smsLog.setId(IdUtils.fas32tUUID());
        smsLog.setType(0);
        smsLog.setMobileCode(code);
        smsLog.setRecDate(DateUtils.getNowDate());
        smsLog.setStatus(1);
        smsLog.setUserId(valueOf.toString());
        smsLog.setUserPhone(mobile);
        smsLog.setContent(content);
        //新增新的验证码
        poloSmsLogMapper.insertPoloSmsLog(smsLog);


        return AjaxResult.success("发送成功！");
    }

    @Override
    public AjaxResult sendEmail(EmailLog em) {
        SimpleMailMessage message = new SimpleMailMessage();
        String mailCode = RandomUtil.randomNumbers(6);
        message.setSubject("科诺电子体温贴邮箱验证码");
        message.setText("验证码是：" + mailCode);
        message.setFrom("kernel@kernelmed.com");
        message.setTo(em.getReceiver());
        sender.send(message);
        em.setVerifyCode(mailCode);
        redisCache.setCacheObject(em.getReceiver(),mailCode);
        redisCache.expire(em.getReceiver(),300);
        return AjaxResult.success(em);
    }

    @Override
    public AjaxResult resetPassword(EmailLog em) {
        //获取redis缓存有效的时间
        Long lg = redisCache.getExpire(em.getReceiver());
        if(lg<=0){
            return AjaxResult.error("验证码过期");
        }
        //获取redis缓存的值
        String s = redisCache.getCacheObject(em.getReceiver());
        if(!em.getVerifyCode().equals(s)){
            return AjaxResult.error("验证码不正确");
        }
        userService.resetUserPwd(em.getReceiver(), SecurityUtils.encryptPassword(em.getPassword()));
        return AjaxResult.success("修改成功");
    }

    @Override
    public AjaxResult resetQuePass(EmailLog em) {

        userService.resetUserPwd(em.getUsername(), SecurityUtils.encryptPassword(em.getPassword()));
        return AjaxResult.success("修改成功");
    }

    /**
     * 互亿验证码平台
     * @param mobile
     */
    private void sendHuYISms(String mobile, String content) {

        String myUrl = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
        Map mp = Maps.newHashMap();
        mp.put("account", "C44330911");
        mp.put("password", "d47dc85d90a082c3c8663736bba00a88");
        mp.put("mobile", mobile);
        mp.put("content", content);
        String str = HttpUtil.post(myUrl,mp);
        System.out.println("------------------------------------------------"+str);
    }
    private void sendCurSms(String mobile, String templateCode, Map<String, String> hashMap) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient需要的几个参数
        final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
        //替换成你的AK
        final String accessKeyId = "LTAI5t7cpVP2S3xnWTMaXy1o";//你的accessKeyId
        final String accessKeySecret = "WW5mvRqg20aC1djo1ClV672WZR2QwO";//你的accessKeySecret
        //初始化ascClient,暂时不支持多region（请勿修改）
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        //必填:待发送手机号
        sendSmsRequest.setPhoneNumbers(mobile);
        //必填:短信签名-可在短信控制台中找到
        sendSmsRequest.setSignName("泰享乐");
        //必填:短信模板-可在短信控制台中找到
        sendSmsRequest.setTemplateCode(templateCode);
        sendSmsRequest.setTemplateParam(JsonUtil.toJsonString(hashMap));


        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(sendSmsRequest);
        if (sendSmsResponse.getCode() == null || !"OK".equals(sendSmsResponse.getCode())) {
            throw new RuntimeException("发送短信失败，请稍后再试:" + sendSmsResponse.getMessage());
        }

    }

    public String formatContent(SmsMy smsMy,Map<String,String> params){
        if(CollectionUtil.isEmpty(params)){
            return smsMy.getContent();
        }
        String content = smsMy.getContent();
        for (Map.Entry<String,String> element : params.entrySet()) {
            content = content.replace("${" + element.getKey() + "}",element.getValue());
        }
        return content;
    }


}
